<template>
  <div class="medications-container">
    <h1>药物清单管理</h1>
    <p class="subtitle">请录入患者当前使用的所有药物</p>
    
    <div class="form-section">
      <h2>添加新药物</h2>
      <div class="form-group">
        <label for="drugName">药物名称:</label>
        <input 
          id="drugName"
          v-model="newMedication.name" 
          type="text" 
          @input="checkDrugName"
          placeholder="请输入药物名称（支持中英文）" 
          class="form-input"
        />
        
        <!-- 药物名称建议列表 -->
        <div v-if="drugSearchResults.length > 0" class="drug-suggestions">
          <div 
            v-for="drug in drugSearchResults" 
            :key="drug.rxcui" 
            @click="selectDrug(drug)"
            class="drug-suggestion-item"
          >
            <strong>{{ drug.name }}</strong> (RxCUI: {{ drug.rxcui }})
          </div>
        </div>
        
        <!-- 搜索状态提示 -->
        <div v-if="drugSearchLoading" class="search-status">
          搜索中...
        </div>
        
        <div v-if="drugSearchError" class="search-error">
          {{ drugSearchError }}
        </div>
      </div>
      
      <div class="form-group">
        <label for="dosage">剂量:</label>
        <input 
          id="dosage"
          v-model="newMedication.dosage" 
          type="text" 
          placeholder="例如: 100mg" 
          class="form-input"
        />
      </div>
      
      <div class="form-group">
        <label for="frequency">频次:</label>
        <input 
          id="frequency"
          v-model="newMedication.frequency" 
          type="text" 
          placeholder="例如: 每日一次" 
          class="form-input"
        />
      </div>
      
      <div class="form-group">
        <label for="route">给药途径:</label>
        <input 
          id="route"
          v-model="newMedication.route" 
          type="text" 
          placeholder="例如: 口服" 
          class="form-input"
        />
      </div>
      
      <button @click="addMedication" class="add-btn">添加药物</button>
    </div>
    
    <div class="medications-list">
      <h2>当前药物清单</h2>
      <div v-if="medications.length === 0" class="no-medications">
        <p>暂无药物记录</p>
      </div>
      <div v-else class="medications-grid">
        <div 
          v-for="medication in medications" 
          :key="medication.id" 
          class="medication-card"
        >
          <h3>{{ medication.name }}</h3>
          <p><strong>剂量:</strong> {{ medication.dosage }}</p>
          <p><strong>频次:</strong> {{ medication.frequency }}</p>
          <p><strong>给药途径:</strong> {{ medication.route }}</p>
          <div v-if="medication.rxcui" class="rxnorm-info">
            <p><strong>RxNorm ID:</strong> {{ medication.rxcui }}</p>
          </div>
          <button @click="removeMedication(medication.id)" class="remove-btn">删除</button>
        </div>
      </div>
    </div>
    
    <div class="navigation-buttons">
      <button @click="goToNext" class="next-btn">确认并进入相互作用检测</button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
// @ts-ignore
import { useStore } from 'vuex'
import { rxnormService, tencentTranslateService } from '@/services/index'

// 定义药物接口
interface Medication {
  id: number
  name: string
  dosage: string
  frequency: string
  route: string
  rxcui?: string
}

const router = useRouter()
const store = useStore()

// 新药物表单数据
const newMedication = ref({
  name: '',
  dosage: '',
  frequency: '',
  route: '',
  rxcui: undefined as string | undefined
})

// 药物搜索相关状态
const drugSearchResults = ref<Array<{rxcui: string, name: string}>>([]);
const drugSearchLoading = ref(false);
const drugSearchError = ref('');

// 从Vuex store获取药物清单
const medications = computed(() => store.state.medications);

// 从localStorage加载药物清单
const loadMedications = () => {
  // 移除localStorage持久化，仅在内存中保存数据
  // const saved = localStorage.getItem('medications');
  // if (saved) {
  //   medications.value = JSON.parse(saved);
  // }
}

// 在组件挂载时加载药物数据
onMounted(() => {
  loadMedications();
})

// 检查药物名称
const checkDrugName = async () => {
  if (newMedication.value.name.length < 2) {
    drugSearchResults.value = [];
    return;
  }
  
  drugSearchLoading.value = true;
  drugSearchError.value = '';
  
  try {
    // 如果是中文药物名称，先翻译为英文再搜索
    let searchName = newMedication.value.name;
    if (/[\u4e00-\u9fa5]/.test(newMedication.value.name)) {
      try {
        const translatedName = await tencentTranslateService.translateText(newMedication.value.name, 'en');
        // 验证翻译结果是否合理（包含英文字母且不是单个字）
        if (translatedName && /[a-zA-Z]/.test(translatedName) && translatedName.trim().length > 1) {
          searchName = translatedName.trim();
          console.log(`中文药物名称 "${newMedication.value.name}" 翻译为英文: "${searchName}"`);
        } else {
          console.warn(`翻译结果不合理，使用原始中文名称进行搜索: "${newMedication.value.name}"`);
        }
      } catch (translationError) {
        console.warn('翻译药物名称时出错，使用原始名称进行搜索:', translationError);
      }
    }
    
    const response = await rxnormService.getApproximateMatch(searchName, 5);
    
    if (response.approximateGroup && response.approximateGroup.candidate) {
      // 对搜索结果进行处理，确保药物名称完整且合理
      drugSearchResults.value = response.approximateGroup.candidate
        .filter((candidate: any) => {
          // 过滤掉明显不合理的药物名称（如只有一个字）
          return candidate.name && candidate.name.length > 1;
        })
        .map((candidate: any) => ({
          rxcui: candidate.rxcui,
          name: candidate.name
        }));
    } else {
      drugSearchResults.value = [];
    }
  } catch (error) {
    drugSearchError.value = '搜索药物时出错，请稍后重试';
    console.error('药物搜索错误:', error);
  } finally {
    drugSearchLoading.value = false;
  }
}

// 选择药物
const selectDrug = async (drug: {rxcui: string, name: string}) => {
  // 直接使用RxNorm提供的名称并确保翻译为中文
  let finalName = drug.name;
  
  try {
    // 如果名称是英文，翻译为中文
    if (/^[A-Za-z\s]+$/.test(drug.name)) {
      finalName = await translateDrugNameToChinese(drug.name);
    } 
    // 如果名称已经是中文但不完整，尝试使用RxCUI获取标准名称
    else if (/[\u4e00-\u9fa5]/.test(drug.name) && drug.name.length <= 2) {
      if (drug.rxcui) {
        try {
          const standardName = await rxnormService.getDisplayName(drug.rxcui);
          if (standardName && standardName.length > drug.name.length) {
            // 如果标准名称更长且合理，使用标准名称
            finalName = await translateDrugNameToChinese(standardName);
          }
        } catch (error) {
          console.warn('获取标准药物名称失败:', error);
        }
      }
    }
  } catch (error) {
    console.error('处理药物名称时出错:', error);
  }
  
  newMedication.value.name = finalName;
  newMedication.value.rxcui = drug.rxcui;
  drugSearchResults.value = [];
}

// 翻译药物名称为中文
const translateDrugNameToChinese = async (drugName: string): Promise<string> => {
  // 如果输入为空，直接返回
  if (!drugName) {
    return drugName;
  }
  
  // 如果已经是中文且长度合理，直接返回
  if (/[\u4e00-\u9fa5]/.test(drugName) && drugName.length > 1) {
    return drugName;
  }
  
  // 如果是中文但只有一个字符，可能是翻译错误，尝试直接返回
  if (/[\u4e00-\u9fa5]/.test(drugName) && drugName.length <= 1) {
    console.warn(`药物名称 "${drugName}" 过短，可能是翻译错误，使用原始输入`);
    return drugName;
  }
  
  try {
    // 调用腾讯翻译服务将英文药物名翻译成中文
    const translatedName = await tencentTranslateService.translateText(drugName, 'zh');
    // 验证翻译结果是否合理（包含中文字符且长度大于1）
    if (translatedName && /[\u4e00-\u9fa5]/.test(translatedName) && translatedName.trim().length > 1) {
      // 额外检查是否为无意义的翻译结果
      const unreasonableTranslations = ['的', '了', '在', '是', '有', '和', '或', '但', '而', '然', '即', '若', '如', '为', '以', '所', '且', '也', '就', '便', '才', '可', '个', '种', '类', '型', '性', '化', '剂', '素', '液', '片', '针', '丸', '散', '膏', '丹', '胶', '膜', '栓', '带', '管', '盒', '瓶', '包'];
      const trimmedName = translatedName.trim();
      if (trimmedName.length <= 2 && unreasonableTranslations.includes(trimmedName)) {
        console.warn(`药物名称翻译结果 "${trimmedName}" 可能无意义，使用原始名称: "${drugName}"`);
        return drugName;
      }
      return trimmedName;
    } else {
      console.warn(`药物名称翻译结果不合理 "${translatedName}"，使用原始名称: "${drugName}"`);
      return drugName;
    }
  } catch (error) {
    // 记录错误信息以便调试
    console.error('翻译药物名称时出错:', error);
    // 出错时安全地返回原始药物名称，防止阻塞主流程
    return drugName;
  }
};

// 添加药物
const addMedication = async () => {
  if (!newMedication.value.name || !newMedication.value.dosage || !newMedication.value.frequency || !newMedication.value.route) {
    alert('请填写完整的药物信息');
    return;
  }
  
  // 确保药物名称为中文
  let finalName = newMedication.value.name;
  
  try {
    // 无论是否有RxCUI，都确保药物名称为中文
    finalName = await translateDrugNameToChinese(newMedication.value.name);
    
    // 如果有RxCUI且当前名称不合理，尝试获取标准药物名称并翻译为中文
    if (newMedication.value.rxcui) {
      // 检查当前名称是否合理（长度过短或明显不完整）
      const isNameUnreasonable = !finalName || 
        finalName.length <= 2 || 
        (finalName.length <= 10 && /^[A-Z]+$/.test(finalName)); // 全大写且短的可能是代码而非药物名
      
      if (isNameUnreasonable) {
        try {
          const standardName = await rxnormService.getDisplayName(newMedication.value.rxcui);
          if (standardName && standardName.length > 1) {
            // 将标准名称翻译为中文
            const translatedStandardName = await translateDrugNameToChinese(standardName);
            if (translatedStandardName && translatedStandardName.length > 1) {
              finalName = translatedStandardName;
            }
          }
        } catch (error) {
          console.warn('获取标准药物名称失败:', error);
          // 获取标准名称失败时，继续使用已翻译的输入名称
        }
      }
    }
  } catch (error) {
    console.error('处理药物名称时出错:', error);
    // 出错时使用原始输入名称
    finalName = newMedication.value.name;
  }
  
  // 检查是否已存在相同的药物（通过RxNorm的allrelated接口）
  let isDuplicate = false;
  if (newMedication.value.rxcui) {
    try {
      // 获取当前药物的所有相关信息
      const relatedInfo = await rxnormService.getAllRelatedInfo(newMedication.value.rxcui);
      
      // 检查现有的药物清单中是否已存在相关的药物
      for (const existingMed of medications.value) {
        if (existingMed.rxcui && relatedInfo.allRelatedGroup && relatedInfo.allRelatedGroup.conceptGroup) {
          // 遍历所有相关概念组
          for (const conceptGroup of relatedInfo.allRelatedGroup.conceptGroup) {
            if (conceptGroup.conceptProperties) {
              // 检查当前相关概念中是否包含已存在的药物RxCUI
              const isRelated = conceptGroup.conceptProperties.some(
                (concept: any) => concept.rxcui === existingMed.rxcui
              );
              if (isRelated) {
                isDuplicate = true;
                break;
              }
            }
          }
        }
        if (isDuplicate) break;
      }
    } catch (error) {
      console.error('检查药物重复时出错:', error);
      // 出错时继续添加药物，避免阻塞用户操作
    }
  }
  
  // 如果是重复药物，提示用户
  if (isDuplicate) {
    alert('该药物已存在于清单中（可能是不同名称的同一种药物）');
    return;
  }
  
  const medication: Medication = {
    id: Date.now(),
    name: finalName, // 使用处理后的最终中文名称
    dosage: newMedication.value.dosage,
    frequency: newMedication.value.frequency,
    route: newMedication.value.route,
    rxcui: newMedication.value.rxcui
  };
  
  // 将药物添加到Vuex store
  store.dispatch('addMedication', medication);
  
  // 清空表单
  newMedication.value.name = '';
  newMedication.value.dosage = '';
  newMedication.value.frequency = '';
  newMedication.value.route = '';
  newMedication.value.rxcui = undefined;
  
  // 清空搜索结果
  drugSearchResults.value = [];
  
  // 移除localStorage持久化，仅在内存中保存数据
  // localStorage.setItem('medications', JSON.stringify(medications.value));
}

// 删除药物
const removeMedication = (id: number) => {
  // 从Vuex store中删除药物
  store.dispatch('removeMedication', id);
  // medications.value = medications.value.filter(med => med.id !== id);
  // 移除localStorage持久化，仅在内存中保存数据
  // localStorage.setItem('medications', JSON.stringify(medications.value));
}

// 导航到下一页
const goToNext = () => {
  router.push('/interactions');
}
</script>

<style scoped>
.medications-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 30px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.medications-container h1 {
  text-align: center;
  color: #2c3e50;
  margin-bottom: 10px;
  font-size: 2rem;
}

.subtitle {
  text-align: center;
  color: #7f8c8d;
  margin-bottom: 30px;
  font-size: 1.1rem;
}

.form-section {
  background: #f8f9fa;
  padding: 30px;
  border-radius: 10px;
  margin-bottom: 30px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.08);
}

.form-section h2 {
  color: #2c3e50;
  margin-top: 0;
  border-bottom: 2px solid #3498db;
  padding-bottom: 10px;
  font-size: 1.5rem;
}

.form-group {
  margin-bottom: 25px;
}

label {
  display: block;
  margin-bottom: 8px;
  font-weight: 600;
  color: #2c3e50;
  font-size: 1rem;
}

.form-input {
  width: 100%;
  padding: 14px;
  border: 2px solid #ddd;
  border-radius: 6px;
  font-size: 1rem;
  transition: border-color 0.3s;
  background: #ffffff;
  box-sizing: border-box;
}

.form-input:focus {
  border-color: #3498db;
  outline: none;
  box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
}

.drug-suggestions {
  background: white;
  border: 1px solid #ddd;
  border-top: none;
  border-radius: 0 0 6px 6px;
  max-height: 200px;
  overflow-y: auto;
  position: relative;
  z-index: 10;
  box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}

.drug-suggestion-item {
  padding: 12px 15px;
  cursor: pointer;
  border-bottom: 1px solid #eee;
  transition: background-color 0.2s;
}

.drug-suggestion-item:hover {
  background-color: #f1f8ff;
}

.drug-suggestion-item:last-child {
  border-bottom: none;
}

.drug-suggestion-item strong {
  color: #2c3e50;
}

.search-status, .search-error {
  padding: 15px;
  margin-top: 10px;
  border-radius: 6px;
  text-align: center;
  font-weight: 500;
}

.search-status {
  background-color: #e3f2fd;
  color: #1976d2;
}

.search-error {
  background-color: #ffebee;
  color: #c62828;
}

.add-btn {
  background-color: #27ae60;
  color: white;
  border: none;
  padding: 14px 28px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 1.1rem;
  font-weight: 600;
  width: 100%;
  transition: all 0.3s;
  box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}

.add-btn:hover {
  background-color: #219653;
  transform: translateY(-2px);
  box-shadow: 0 6px 8px rgba(0,0,0,0.15);
}

.medications-list h2 {
  color: #2c3e50;
  margin-top: 0;
  border-bottom: 2px solid #2ecc71;
  padding-bottom: 10px;
  font-size: 1.5rem;
}

.medications-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 25px;
  margin-top: 20px;
}

.medication-card {
  background: white;
  border-radius: 10px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.08);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  border-left: 5px solid #3498db;
}

.medication-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 15px rgba(0,0,0,0.12);
}

.medication-card h3 {
  margin-top: 0;
  color: #2c3e50;
  font-size: 1.3rem;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.medication-card p {
  margin: 10px 0;
  color: #555;
  font-size: 0.95rem;
}

.medication-card strong {
  color: #2c3e50;
}

.rxnorm-info {
  background-color: #e3f2fd;
  padding: 10px;
  border-radius: 6px;
  margin-top: 15px;
  font-size: 0.9rem;
}

.rxnorm-info p {
  margin: 5px 0;
  color: #1976d2;
}

.remove-btn {
  background-color: #e74c3c;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.9rem;
  margin-top: 15px;
  transition: background-color 0.3s;
  font-weight: 500;
}

.remove-btn:hover {
  background-color: #c0392b;
}

.navigation-buttons {
  text-align: center;
  margin-top: 40px;
  padding: 30px 0;
  border-top: 1px solid #eee;
}

.next-btn {
  background-color: #3498db;
  color: white;
  border: none;
  padding: 14px 28px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 1.1rem;
  font-weight: 600;
  transition: all 0.3s;
  box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}

.next-btn:hover {
  background-color: #2980b9;
  transform: translateY(-2px);
  box-shadow: 0 6px 8px rgba(0,0,0,0.15);
}

@media (max-width: 768px) {
  .medications-container {
    padding: 20px;
  }
  
  .form-section {
    padding: 20px;
  }
  
  .medications-grid {
    grid-template-columns: 1fr;
  }
  
  .medication-card {
    padding: 15px;
  }
  
  .next-btn {
    width: 100%;
    padding: 12px;
  }
}
</style>